package cn.tedu.medicalmanagementsystem.user.service.impl;

import cn.tedu.medicalmanagementsystem.base.response.JsonResult;
import cn.tedu.medicalmanagementsystem.base.response.StatusCode;
import cn.tedu.medicalmanagementsystem.escort.pojo.entity.Escort;
import cn.tedu.medicalmanagementsystem.user.mapper.UserMapper;
import cn.tedu.medicalmanagementsystem.user.pojo.dto.UserLoginParam;
import cn.tedu.medicalmanagementsystem.user.pojo.entity.User;
import cn.tedu.medicalmanagementsystem.user.pojo.vo.UserVO;
import cn.tedu.medicalmanagementsystem.user.service.UserLoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    private final UserMapper userMapper;
    @Autowired
    public UserLoginServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public JsonResult<UserVO> login(UserLoginParam userLoginParam) {
        // 1. 参数校验
        if (userLoginParam == null || StringUtils.isEmpty(userLoginParam.getPhone())) {
            return JsonResult.fail(StatusCode.PARAMETER_ERROR);
        }

        // 2. 查询用户信息（改用 selectByPhoneAndPassword）
        UserVO userVO = userMapper.selectByPhoneAndPassword(userLoginParam);

        if (userVO == null) {
            return JsonResult.fail(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        return JsonResult.success(userVO);
    }

    @Override
    public UserVO getUserById(Long userId) {
        if (userId == null || userId <= 0) {
            return null;
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return null;
        }

        return convertToVO(user);
    }

    /**
     * 将User实体转换为UserVO
     */
    private UserVO convertToVO(User user) {
        if (user == null) {
            return null;
        }

        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);

        return vo;
    }
}
